﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DTD2013.Entities;
using DTD2013.Common;
using DTD2013.DTDLib;
using System.IO;
using DTD2013.MainApp.Properties;
using DevExpress.XtraEditors;
using DTD2013.MainApp.UI;

namespace DTD2013.MainApp
{
    public partial class Startup : RibbonForm
    {
        #region Properties


        #endregion

        #region Variable

        /// <summary>
        /// Count of document number has created
        /// </summary>
        private static int DocumentCount = 0;

        #endregion

        #region Constructor

        public Startup()
        {
            InitializeComponent();
            LoadTheme();
            bliRecentFilePath.ListItemClick += new ListItemClickEventHandler(bliRecentFilePath_ListItemClick);
            mdiDeluxe.SelectedPageChanged += new EventHandler(mdiDeluxe_SelectedPageChanged);
        }

        private void mdiDeluxe_SelectedPageChanged(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild != null)
            {
                bciAutoCalculate.EditValue = (this.ActiveMdiChild as Deluxe).AutoCalculateKL;
            }
        }

        private void bliRecentFilePath_ListItemClick(object sender, ListItemClickEventArgs e)
        {
            string filePath = bliRecentFilePath.Strings[e.Index];
            if (!File.Exists(filePath))
            {
                if (XtraMessageBox.Show(MessageResource.FILE_NOT_EXIST, MessageResource.ERROR,
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    // Remove file path
                    DataUtilities.RemoveRecentFilePath(filePath);
                    LoadRecentFile();
                }
            }
            else
            {
                splashWaitingScreen.ShowWaitForm();
                Deluxe dtd = new Deluxe();
                dtd.MdiParent = this;
                dtd.FilePath = filePath;
                dtd.Text = filePath.Substring(filePath.LastIndexOf("\\"))
                                   .Replace("\\", string.Empty).Split('.')[0];
                dtd.LoadDTDFromFile(filePath);
                dtd.StatusFile = FileStatus.Open;
                dtd.FileSaved = true;
                dtd.Show();
                splashWaitingScreen.CloseWaitForm();
            }
        }

        private void Startup_Load(object sender, EventArgs e)
        {
            LoadRecentFile();
        }

        #endregion

        #region Show message

        /// <summary>
        /// Alert error message when error occur
        /// </summary>
        /// <param name="message">Message content</param>
        public void ShowErrorMessage(string message)
        {
            if (bciShowAlert.Checked)
            {
                alertMessageControl.Show(this, MessageResource.ERROR, message, Resources.error);
            }
        }

        /// <summary>
        /// Alert error message when error occur
        /// </summary>
        /// <param name="owner">Form containt alert message</param>
        /// <param name="caption">Header caption</param>
        /// <param name="message">Message content</param>
        public void ShowErrorMessage(Form owner, string caption, string message)
        {
            alertMessageControl.Show(owner, caption, message, Resources.error);
        }

        /// <summary>
        /// Alert success message
        /// </summary>
        /// <param name="message">Message content</param>
        public void ShowSuccessMessage(string message)
        {
            if (bciShowAlert.Checked)
            {
                alertMessageControl.Show(this, MessageResource.SUCCESS, message, Resources.success);
            }
        }

        /// <summary>
        /// Alert success message
        /// </summary>
        /// <param name="owner">Form containt alert message</param>
        /// <param name="caption">Header caption</param>
        /// <param name="message">Message content</param>
        public void ShowSuccessMessage(Form owner, string caption, string message)
        {
            alertMessageControl.Show(owner, caption, message, Resources.success);
        }

        /// <summary>
        /// Alert information message
        /// </summary>
        /// <param name="message">Message content</param>
        public void ShowInfoMessage(string message)
        {
            if (bciShowAlert.Checked)
            {
                alertMessageControl.Show(this, MessageResource.INFORMATION, message, Resources.information);
            }
        }

        /// <summary>
        /// Alert information message
        /// </summary>
        /// <param name="owner">Form containt alert message</param>
        /// <param name="caption">Header caption</param>
        /// <param name="message">Message content</param>
        public void ShowInfoMessage(Form owner, string caption, string message)
        {
            alertMessageControl.Show(owner, caption, message, Resources.information);
        }

        /// <summary>
        /// Alert warning message
        /// </summary>
        /// <param name="message"></param>
        public void ShowWarningMessage(string message)
        {
            if (bciShowAlert.Checked)
            {
                alertMessageControl.Show(this, MessageResource.WARNING, message, Resources.warning);
            }
        }

        /// <summary>
        /// Alert warning message
        /// </summary>
        /// <param name="owner">Form containt alert message</param>
        /// <param name="caption">Header caption</param>
        /// <param name="message">Message content</param>
        public void ShowWarningMessage(Form owner, string caption, string message)
        {
            alertMessageControl.Show(owner, caption, message, Resources.warning);
        }

        /// <summary>
        /// Show question message
        /// </summary>
        /// <param name="message">The message</param>
        public void ShowQuestionMessage(string message)
        {
            if (bciShowAlert.Checked)
            {
                alertMessageControl.Show(this, MessageResource.QUESTION, message, Resources.question);
            }
        }

        /// <summary>
        /// Show question message
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="caption"></param>
        /// <param name="message"></param>
        public void ShowQuestionMessage(Form owner, string caption, string message)
        {
            alertMessageControl.Show(owner, caption, message, Resources.question);
        }

        #endregion

        #region Public method

        /// <summary>
        /// Save the current active deluxe to file
        /// </summary>
        public void SaveCurrentDeluxe()
        {
            bbiSaveFile_ItemClick(null, null);
        }

        public void SetFocusRibbonPage(SelectedRibbonPage selectedPage)
        {
            if (selectedPage == SelectedRibbonPage.HeThong)
            {
                rbMainMenu.SelectedPage = rbpHeThong;
            }
            else if (selectedPage == SelectedRibbonPage.SoanThao)
            {
                rbMainMenu.SelectedPage = rbpSoanThao;
            }
            else if (selectedPage == SelectedRibbonPage.TinhDuToan)
            {
                rbMainMenu.SelectedPage = rbpTinhDT;
            }
            else if (selectedPage == SelectedRibbonPage.InDuToan)
            {
                rbMainMenu.SelectedPage = rbpInDT;
            }
            else if (selectedPage == SelectedRibbonPage.TienIch)
            {
                rbMainMenu.SelectedPage = rbpTienIch;
            }
            else
            {
                rbMainMenu.SelectedPage = rbpGiaoDien;
            }
        }

        #endregion

        #region private method

        private void LoadTheme()
        {
            defaultLookAndFeelThemes.LookAndFeel.SkinName = Settings.Default.Theme;
        }

        private void LoadRecentFile()
        {
            bliRecentFilePath.Strings.Clear();
            DeluxeEntities context = new DeluxeEntities();
            List<RecentFilePath> recentFile = context.RecentFilePaths
                                                     .OrderByDescending(r => r.CreateDate)
                                                     .Take(5).ToList();
            foreach (RecentFilePath file in recentFile)
            {
                bliRecentFilePath.Strings.Add(file.FilePath);
            }
        }

        #endregion

        #region Page He thong

        private void bbiCreateNew_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                splashWaitingScreen.ShowWaitForm();
                DocumentCount++;
                Deluxe dtd = new Deluxe();
                dtd.MdiParent = this;
                dtd.Text = string.Format("{0} {1}", Constant.NEW_DOCUMENT, DocumentCount);
                dtd.FilePath = string.Empty;
                dtd.StatusFile = FileStatus.CreateNew;
                dtd.Show();
                rbMainMenu.SelectedPage = rbpTinhDT;
            }
            catch (Exception ex) { XtraMessageBox.Show(ex.Message); }
            finally { splashWaitingScreen.CloseWaitForm(); }
        }

        private void bbiOpenFile_ItemClick(object sender, ItemClickEventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Filter = Constant.XML_FILTER;
            openDlg.InitialDirectory = Application.ExecutablePath;
            openDlg.Title = Constant.OPEN_FILE_DIALOG_TITLE;
            if (openDlg.ShowDialog() == DialogResult.OK)
            {
                // confirm password
                string pasword = DataUtilities.GetDtdPassword(openDlg.FileName);
                if (!string.IsNullOrEmpty(pasword))
                {
                    guiConfirmPassword confirmPassword = new guiConfirmPassword(pasword);
                    if (confirmPassword.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                }
                try
                {
                    splashWaitingScreen.ShowWaitForm();
                    Deluxe dtd = new Deluxe();
                    dtd.MdiParent = this;
                    dtd.FilePath = openDlg.FileName;
                    dtd.Text = openDlg.FileName
                                      .Substring(openDlg.FileName.LastIndexOf("\\"))
                                      .Replace("\\", string.Empty).Split('.')[0];
                    dtd.LoadDTDFromFile(openDlg.FileName);
                    dtd.StatusFile = FileStatus.Open;
                    dtd.FileSaved = true;
                    dtd.Show();
                    rbMainMenu.SelectedPage = rbpTinhDT;
                }
                catch(Exception ex) { XtraMessageBox.Show(ex.Message); }
                finally { splashWaitingScreen.CloseWaitForm(); }
            }
        }

        private void bbiSaveFile_ItemClick(object sender, ItemClickEventArgs e)
        {
            Deluxe dtd = this.ActiveMdiChild as Deluxe;
            if (dtd != null)
            {
                string filePath = dtd.FilePath;
                if (File.Exists(filePath))
                {
                    dtd.SaveDTDToFile(filePath);
                    dtd.StatusFile = FileStatus.Saved;
                    dtd.FileSaved = true;
                    if (dtd.IsEditNorm)
                    {
                        DialogResult result = MessageBox.Show(MessageResource.SAVE_NORM,
                                                MessageResource.SAVE_NORM_CAPTION, MessageBoxButtons.YesNo,
                                                MessageBoxIcon.Question);
                        if (result == DialogResult.Yes)
                        {
                            dtd.SaveNorm();
                        }
                        dtd.IsEditNorm = false;
                    }
                    ShowSuccessMessage(MessageResource.SAVE_SUCCESS);
                }
                else
                {
                    bbiSaveAs_ItemClick(null, null);
                }
            }
        }

        private void bbiSaveAs_ItemClick(object sender, ItemClickEventArgs e)
        {
            Deluxe dtd = this.ActiveMdiChild as Deluxe;
            if (dtd != null)
            {
                string saveFilePath = DataUtilities.GetSaveFilePath();
                if (!string.IsNullOrEmpty(saveFilePath))
                {
                    dtd.SaveDTDToFile(saveFilePath);
                    dtd.FilePath = saveFilePath;
                    dtd.Text = saveFilePath.Substring(saveFilePath.LastIndexOf("\\"))
                                    .Replace("\\", string.Empty).Split('.')[0];
                    dtd.StatusFile = FileStatus.Saved;
                    dtd.FileSaved = true;
                    if (dtd.IsEditNorm)
                    {
                        DialogResult result = MessageBox.Show(MessageResource.SAVE_NORM,
                                                MessageResource.SAVE_NORM_CAPTION, MessageBoxButtons.YesNo,
                                                MessageBoxIcon.Question);
                        if (result == DialogResult.Yes)
                        {
                            dtd.SaveNorm();
                        }
                        dtd.IsEditNorm = false;
                    }
                    // Add file path to recent path table
                    DataUtilities.AddRecentFilePath(saveFilePath);
                    LoadRecentFile();
                    ShowSuccessMessage(MessageResource.SAVE_SUCCESS);
                }
                else
                {
                    XtraMessageBox.Show(MessageResource.SAVE_PATH_ERROR, MessageResource.ERROR,
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void bbiClose_ItemClick(object sender, ItemClickEventArgs e)
        {
            foreach (Form activeForm in MdiChildren)
            {
                (activeForm as Deluxe).Close();
                if ((activeForm as Deluxe).IsCancel)
                    return;
            }
            this.Close();
        }

        #endregion

        #region Page Tinh du toan

        private void bciAutoCalculate_EditValueChanged(object sender, EventArgs e)
        {
            Deluxe dtd = this.ActiveMdiChild as Deluxe;
            if (dtd != null)
            {
                dtd.AutoCalculateKL = Convert.ToBoolean(bciAutoCalculate.EditValue);
            }
        }

        #endregion

        #region Themes

        private void ribbonGalleryBarItemSkin_ItemClick(object sender, GalleryItemClickEventArgs e)
        {
            Settings.Default.Theme = e.Item.Caption;
            Settings.Default.Save();
            defaultLookAndFeelThemes.LookAndFeel.SkinName = Settings.Default.Theme;
        }

        #endregion        
    }
}